<?php
/**
 * 用户信息结构
 */

namespace App\Services\Member;

use App\Models\Member\Friend;
use App\Models\Member\Level;
use App\Models\Member\Member;
use App\Models\Member\Follow;
use App\Models\Member\Sign;
use App\Services\Com\StatisticsService;
use App\Services\Talking\TalkingService;
use App\Services\Com\UtilService;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class MemberInfoService
{
    /**
     * uuid 要查的人
     * member_uuid 当前登录人
     */
    public static function userInfoByUuid(string $uuid = '', $member_uuid = ''){
        if(empty($uuid)){
            return null;
        }

        $cache_key = config('cache.key_list.userinfo_by_uuid').$uuid;
        $cache_data = Cache::get($cache_key);
        
        if(!empty($cache_data)){
            $row_obj = $cache_data;
        }else{

            $where[] = ['uuid', '=', $uuid];
            $row_obj = Member::select((['id','uuid','mobile_prefix','mobile','email','no','avatar_url','title','created_at',
                'name','sex','nickname','birthday','enabled','state','country_uuid','school_uuid','city_id','online_city_id']))
                ->with([
                    'school'=>function($query){
                        $query->select(['uuid', 'name', 'cn_name', 'state']);
                    }
                ])
                ->with([
                    'country'=>function($query){
                        $query->select(['uuid', 'name', 'mobile_prefix', 'nationalflag', 'code']);
                    }
                ])
                ->with([
                    'works'=>function($query){
                        $query->select(['*']);
                    }
                ])
                ->where($where)
                ->first();
                Cache::put($cache_key, $row_obj, config('cache.ttl_stat'));
        }
        //cache end

        $data = null;
        if(empty($row_obj)){
            return null;
        }else{
            $value = $row_obj->toArray();
            //登录者是否关注此人
            $follow_where = [];
            $follow_where[] = ['member_uuid', '=', $member_uuid];
            $follow_where[] = ['followed_member_uuid', '=', $value['uuid']];
            $follow_count = Follow::where($follow_where)->count();
            
            //此人是否关注登录者
            $attentionMe = MemberService::batchAttention($value['uuid'], [$member_uuid]);
            $attention_me_res = $attentionMe[0]['followed_member_uuid'] ?? '';

            $data = [
                    'uuid'=>$value['uuid'],//用户uuid
                    'im_username'=>UtilService::memberUuidToImAccount($value['uuid']),//用户名
                    'username'=>$value['nickname'],//用户名
                    'avatar'=>$value['avatar_url'],//用户头像
                    'title'=>!empty($value['title']) ? $value['title'] : null,//圈子名称
                    'created_at'=>$value['created_at'],//用户创建时间
                    'online'=>0,//1在线0不在线
                    'country'=>$value['country']['code'] ?? '',//国家名称
                    'country_flag'=>$value['country']['nationalflag'] ?? '',//国家国旗
                    'vip'=>1,//1是0不是
                    'state'=>$value['state'],//'状态 -200认证失败 0待认证 5认证中 200认证通过'
                    'city_id'=>$value['city_id'],//城市id
                    'online_city_id'=>$value['online_city_id'],//在线城市
                    
                    'attention'=>$follow_count >= 1 ? 1 : 0,//我是否关注此人，1是已经关注0，是未关注
                    'is_followed'=>$attention_me_res == $member_uuid ? 1 : 0,//此人是否关注登录者

                    'sex'=> $value['sex'],//性别  1男 2女 0未知
                    'year_of_birth'=> self::yearOfBirth($value['birthday'] ?? ''),//出生年份
                    'works'=> $row_obj->works,//工作经历
                ];
        }
        return $data;
    }

    /**
     *
     * 生日转成 80s 90s 
     **/
    public static function yearOfBirth(string $birthday = ''){
        $year_s = '';
        $b_arr = explode('-', $birthday);
        
        if(strlen($b_arr[0]) == 4){
            $year_s = $b_arr[0][2]."0's";
        }
        return $year_s;
    }

    public static function memberByUuid(string $member_uuid){
        $row = Member::select(['id','uuid','mobile_prefix','mobile','email','no','avatar_url','sex','nickname','birthday','enabled','state',
            'country_uuid','school_uuid','province_id','city_id','area_id','lng','lat','address','introduction','background_url','title','desc','level_uuid','code_num'
            ,'currency','total_currency','money','freeze_money','total_money','name','id_card_no','card_address','wallet_auth_state',
            'openid','appleid','alipay_account','alipay_name','level_number','admission_time','education','follow_state','circle_avatar_url',
            'private_rec','private_ad',
        ])
            ->with([
                'school'=>function($query){
                    $query->select(['uuid', 'name', 'cn_name', 'state']);
                }
            ])
            ->with([
                'schoolManager'=>function($query){
                    $query->with('position')->select(['uuid', 'position_uuid', 'member_uuid', 'school_uuid']);
                }
            ])
            ->with([
                'country'=>function($query){
                    $query->select(['uuid', 'name', 'mobile_prefix', 'nationalflag', 'code']);
                }
            ])
            ->with([
                'province'=>function($query){
                    $query->select(['id', 'name', 'lng', 'lat']);
                }
            ])
            ->with([
                'city'=>function($query){
                    $query->select(['id', 'name', 'lng', 'lat']);
                }
            ])
            ->with([
                'subjects'=>function($query){
                    $query->select(['uuid', 'member_uuid', 'subject']);
                }
            ])
            ->with([
                'attrs'=>function($query){
                    $query->select('*');
                }
            ])
            ->with([
                'medals'=>function($query){
                    $query->with('medal')->where('is_use', 1)->select('*');
                }
            ])
            ->with([
                'works'=>function($query){
                    $query->select(['uuid', 'member_uuid', 'company', 'position']);
                }
            ])
            ->with('level')
            ->with('myTalking')
//            ->with([
//                'friends'=>function($query){
//                    $query->with([
//                        'friend'=>function($query){
//                            $query->select(['uuid', 'nickname', 'avatar_url']);
//                        }
//                    ])->select(['uuid', 'member_uuid', 'friend_member_uuid', 'tab']);
//                }
//            ])
            ->where('uuid', $member_uuid)->first();

        if(!$row) throw new \Exception('用户信息不存在');

        $row = $row->toArray();
        !empty($row['id_card_no']) && $row['id_card_no'] = UtilService::str_hide($row['id_card_no'], 5, 8);

        $row['friends'] = Friend::where('member_uuid', $member_uuid)->select(['uuid', 'member_uuid', 'friend_member_uuid', 'tab'])->with([
            'friend'=>function($query){
                $query->select(['uuid', 'nickname', 'avatar_url']);
            }
        ])->where('tab', '!=', '')->limit(6)->get()->toArray();

        if(empty($row['friends'])) $row['friends'] = Friend::where('member_uuid', $member_uuid)->select(['uuid', 'member_uuid', 'friend_member_uuid', 'tab'])->with([
            'friend'=>function($query){
                $query->select(['uuid', 'nickname', 'avatar_url']);
            }
        ])->limit(6)->get()->toArray();

        $row['city_name'] = '';
        !empty($row['province']) && $row['city_name'] = $row['province']['name'];
        !empty($row['city']) && $row['city_name'] != $row['city']['name'] && $row['city_name'] = $row['city_name'] ? $row['city_name'].'.'.$row['city']['name'] : $row['city']['name'];

        //im编号
        $row['im_username'] = UtilService::memberUuidToImAccount($row['uuid']);

        //用户邀请二维码
        try {
            $qrCode = QrCode::format('png')->size(300)->margin(2)->generate('https://migo.imhaiguiapp.com/h5/#/pages/messageList/shortLink');
//            $qrCode = QrCode::format('png')->size(300)->margin(0)->generate('/app/UserInfoActivity?params_data='.$member_uuid);
//            $qrCode = QrCode::format('png')->size(300)->margin (0)->generate($this->uuid('member'));

//            $row['qrCode'] = UtilService::ossUploadObject('member/qrcode/'.$memd定位ber_uuid.'.png', $qrCode);
            $row['qrCode'] = UtilService::ossUploadObject('member/qrcode/shortLinkss.png', $qrCode);
        }catch (\Exception $e){

        }

        //签到
        $sign = Sign::where('member_uuid', $member_uuid)->orderBy('day', 'desc')->first();
        $row['is_sign'] = $sign && $sign->day == date('Y-m-d') ? 1 : 0;
        $row['today_level_number'] = 1;
        $row['title'] = empty($row['title']) ? $row['nickname'].'的空间' : $row['title'];
        $row['continuity_sign_days'] = $sign && $sign->day == date('Y-m-d') ? $sign->continuity_sign_days : 0;
        $row['tomorrow_level_number'] = 1;

        $row['level_next'] = Level::where('level', '>', $row['level']['level'])->orderBy('level', 'asc')->first();

        $row['statistics'] = StatisticsService::getByMember($member_uuid);

        return $row;
    }
}